﻿using DataWorks_Sqlite.MappingClass;
using DataWorks_Tools.BasicMethods;
using DataWorks_Tools.HalfHourCalSave.BinImort;
using DataWorks_Tools.HalfHourCalSave.Common.DataImport;
using DataWorks_Tools.MappModals;
using DataWorks_Tools.MappModals.CalInputModals;
using DataWorks_Tools.MappModals.CalSaveModals;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static DataWorks_Tools.HalfHourCalSave.Common.Basic.EnumClass;

namespace DataWorks_Tools.HalfHourCalSave
{
    public static class MileageCalSaveMethods
    {
        static string[] filenames = new string[]
       {
            "dia_import_permileage.csv",
            "dia_import_record.csv"
       };
        public static async Task<List<string>> YXHExcuteMileageSaveMultiThreadAsync(MileageCalInputModel row,  dw_props_admin admin)
        {
            List<string> result = new List<string>
            {
                "开始进行单位里程计算"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            };//专用于输出程序计算过程中的错误信息
              //获得用户输入的日期和路径下的日期文件夹名称相同的文件夹
            var sd = Convert.ToDateTime(row.startdate);
            var ed = Convert.ToDateTime(row.enddate);
            if(sd.Year!=ed.Year)
            {
                var noinfo = $"注意：不能跨年！！！ {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}{Environment.NewLine}";
                result.Add(noinfo);
                return result;
            }
            var directories = DateTimeMethods.YXHGetDirectoryArrayfromDate(row);
            if (directories.Length > 0)
            {
                Stopwatch Stimer = new Stopwatch();
                Stimer.Start();
                List<Task> tasks = new List<Task>();
                foreach (var d in directories)
                {
                    var dirname = new DirectoryInfo(d).Name;
                    result.Add($"开始进行{dirname}下的单位里程计算  {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    Task task = Task.Run(async () => {
                        Stopwatch dtimer = new Stopwatch();
                        dtimer.Start();
                        var csvfiles = d.YXHGetAllextFiles("*.csv");
                        var csvyear = csvfiles.First().Name.Split('_')[0];
                        var csvdate = csvfiles.First().Name.Split('-')[0];
                        //DateTime date = DateTime.ParseExact(csvdate, "yyyy_MM_dd", CultureInfo.InvariantCulture);
                        //转为int的年份
                        int.TryParse(csvyear, out var year);
                        if (year == sd.Year || year == ed.Year)
                        {
                            if (csvfiles.Length > 0)
                            {
                                List<calsave_permileage_split> mileagelist = new List<calsave_permileage_split>();
                                List<calsave_record> recordlist = new List<calsave_record>();
                                foreach (var csvfile in csvfiles)
                                {
                                    if (csvfile.FullName.YXHFileIsZero())
                                    {
                                        result.Add($"{new DirectoryInfo(d).Name}下的{csvfile.Name}文件大小为0kb");
                                        return ;
                                    };
                                    var data = await ReadfromCSV.GetDatafromCSVAsync(csvfile);
                                    if (data.status == 0)
                                    {
                                        var list = await Tools_StatisticImport.GetPerMileageStatisticAsync(data, row, admin.binnumber);
                                        mileagelist.AddRange(list);
                                    }
                                    else
                                    {
                                        var error = data.status == 1 ? "有空值或NaN" : data.status == 2 ? "不是数字" : "文件被占用";
                                        var info = $"{row.vehicle}文件夹{dirname}的{csvfile.Name}的列名为{data.errorname}行号为{data.errorrow}单位里程统计时出现了错误为{error} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}{Environment.NewLine}";
                                        result.Add(info);
                                        return;
                                    }
                                }
                                //以下是添加记录表的数据
                                if (mileagelist.Count > 0)
                                {
                                    var record = Tools_RecordImport.GetImportRecord(row, year, dirname, (byte)ImportType.permileagestatistics);
                                    recordlist.Add(record);
                                }
                               
                                //先创建输出文件夹
                                var newsavepath = row.savepath.YXHPathReplace();
                                Directory.CreateDirectory(newsavepath);
                                var newsavedir = Path.Combine(newsavepath, dirname);
                                //result.Add($"开始进行{dirname}文件半小时保存  {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                                //保存csv
                                await YXHCreateCSVAsync(mileagelist, recordlist, newsavedir);
                                //result.Add($"{dirname}文件半小时保存完毕  {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                                dtimer.Stop();
                                result.Add($"{dirname}单位里程计算完成时间为{dtimer.Elapsed.TotalMinutes:0.00}分");
                            }
                        }
                        else
                        {
                            var noinfo = $"你选的年份和csv文件的年份不相等，请重新选择日期 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}{Environment.NewLine}";
                            result.Add(noinfo);
                            return ;
                        }
                    });
                    tasks.Add(task);
                }
                await Task.WhenAll(tasks.ToArray());
                Stimer.Stop();
                result.Add($"单位里程计算完成总时间为{Stimer.Elapsed.TotalMinutes:0.00}分");
            }
            else
            {
                var noinfo = $"你选的路径{row.inputpath}没有{row.vehicle}的数据 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}{Environment.NewLine}";
                result.Add(noinfo);
            }
            return result;
        }

      
        public static async Task YXHCreateCSVAsync(List<calsave_permileage_split> list, List<calsave_record> recordlist,string savepath)
        {
            try
            {
                await CSVHelperClass.SaveCSVfromListTData(list, Path.Combine(savepath, filenames[0]));
                await CSVHelperClass.SaveCSVfromListTData(recordlist, Path.Combine(savepath, filenames[1]));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

        }
    }
}
